<template>
    <el-container class="home-page">
      <!-- My Books Section -->
      <el-container v-if="books" class="my-book-list" style="margin-bottom: 40px;">
        <el-header>
          <h2>我的文章</h2>
        </el-header>
        <el-main class="el-main-book">
          <div
            v-for="(book, index) in books"
            :key="index"
            class="book-card"
            style="margin-bottom: 20px;"
          >
            <el-card shadow="hover" class="book-card-content" @click="viewBook(book)">
              <div class="book-thumbnail-wrapper">
                <ElImage
                  :src="book.coverImageUrl"
                  :alt="book.title"
                  class="book-thumbnail"
                />
              </div>
              <div class="book-info-wrapper">
                <div>
                  <el-tooltip content="View Book" placement="top">
                    <h3 class="book-title">{{ book.title }}</h3>
                  </el-tooltip>
                  <p class="book-details">
                    查看数: {{ book.views }} | 点赞数: {{ book.likes }}
                  </p>
                </div>
              </div>
            </el-card>
          </div>
         
        </el-main>
         <!-- Pagination for Books -->
         <el-pagination
         background
         layout="prev, pager, next"
         :total="totalBooks"
         :page-size="bookPageSize"
         v-model:current-page="bookPage"
         @current-change="handleBookPageChange"
         style="margin-top: 10px; text-align: center;"
       />
      </el-container>
  
      <!-- My Articles Section (Card-Based Layout) -->
      <el-container class="my-article-list" style="margin-bottom: 40px;">
        <el-header>
          <h2>我的书本</h2>
        </el-header>
        <el-main>
          <div v-for="(article, index) in articles" :key="index" style="margin-bottom: 20px;">
            <el-card shadow="hover">
              <div style="display: flex; align-items: center; justify-content: space-between;">
                <div>
                  <h3>{{ article.title }}</h3>
                  <p>作者: {{ article.author || "NaN" }} | 日期: {{ article.lastUpdateDate || "NaN" }}</p>
                </div>
                <el-button @click="viewArticle(article)" type="primary" plain>查看</el-button>
              </div>
            </el-card>
          </div>
          <!-- Pagination for Articles -->
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalArticles"
            :page-size="articlePageSize"
            v-model:current-page="articlePage"
            @current-change="handleArticlePageChange"
            style="margin-top: 10px; text-align: center;"
          />
        </el-main>
      </el-container>
  
      <!-- My Likes Section with Dropdown to Toggle Between Liked Articles and Liked Data -->
      <el-container class="my-like-list">
        <el-header>
          <h2>我的收藏</h2>
        </el-header>
        <el-main>
          <!-- Dropdown to select Liked Articles or Liked Data -->
          <el-select v-model="selectedLikeType" placeholder="Select Type" style="width: 200px; margin-bottom: 20px;">
            <el-option label="文章" value="articles"></el-option>
            <el-option label="数据" value="data"></el-option>
          </el-select>
  
          <!-- Conditionally Render Based on Selected Dropdown Option -->
          <template v-if="selectedLikeType === 'articles'">
            <!-- Liked Articles -->
            <div v-for="(article, index) in likedArticles" :key="index" style="margin-bottom: 20px;">
              <el-card shadow="hover">
                <div style="display: flex; align-items: center; justify-content: space-between;">
                  <div>
                    <h3>{{ article.title }}</h3>
                    <p>作者: {{ article.author || "NaN" }} | 日期: {{ article.lastUpdateDate || "NaN" }}</p>
                  </div>
                  <el-button @click="viewLikedArticle(article)" type="primary" plain>查看</el-button>
                </div>
              </el-card>
            </div>
            <!-- Pagination for Liked Articles -->
            <el-pagination
              background
              layout="prev, pager, next"
              :total="totalLikedArticles"
              :page-size="likedArticlePageSize"
              v-model:current-page="likedArticlePage"
              @current-change="handleLikedArticlePageChange"
              style="margin-top: 10px; text-align: center;"
            />
          </template>
  
          <template v-else-if="selectedLikeType === 'data'">
            <!-- Liked Data -->
            <div v-for="(data, index) in likedData" :key="index" style="margin-bottom: 20px;">
              <el-card shadow="hover">
                <img :src="data.thumbnail" alt="data thumbnail" class="like-thumbnail" />
                <div style="padding: 10px;">
                  <el-tooltip content="View Data" placement="top">
                    <span class="like-title">{{ data.title }}</span>
                  </el-tooltip>
                  <el-button @click="viewLikedData(data)" type="text" style="float: right;">View</el-button>
                </div>
              </el-card>
            </div>
            <!-- Pagination for Liked Data -->
            <el-pagination
              background
              layout="prev, pager, next"
              :total="totalLikedData"
              :page-size="likedDataPageSize"
              v-model:current-page="likedDataPage"
              @current-change="handleLikedDataPageChange"
              style="margin-top: 10px; text-align: center;"
            />
          </template>
        </el-main>
      </el-container>
    </el-container>
  </template>
  
  
  <script setup lang="ts">
  import { ref, onMounted,defineProps } from 'vue';
  import axios from 'axios';
import router from '@/router';
import { ElImage } from 'element-plus';
  
const props = defineProps({
    userId:{
        type:Number,
        required:true
    },
  
})
  // 定义接口类型
  interface Book {
  id: number;                   // 书籍的唯一标识符
  title: string;                // 书籍名称
  type: number;                 // 书籍的类型（如1代表科幻，2代表奇幻）
  authorId: number;             // 与作者关联的唯一标识符
  authorName?: string;          // 书籍的作者名称（可选，因Java类中有待添加）
  likes: number;                // 书籍的点赞数量
  favorites: number;            // 收藏书籍的用户数量
  views: number;                // 书籍的浏览次数
  status: number;               // 当前书籍的状态，如"连载中"或"完结"
  publishDate: string;          // 书籍的发布日期 (ISO 8601字符串格式)
  lastUpdateDate: string;       // 书籍的最后更新时间 (ISO 8601字符串格式)
  wordCount: number;            // 书籍的总字数
  rating: number;               // 用户对书籍的评分，0到5之间的小数
  summary: string;              // 书籍的简要描述
  coverImageUrl: string;        // 书籍封面图片的URL链接
  commentsCount: number;        // 用户对书籍的评论数量
  price: number;                // 书籍的价格，适用于付费书籍
  latestChapter: number;        // 书籍的最新章节编号
  reviewStatus: number;         // 书籍的审核状态
  reviewText: string;           // 审核的文本描述
}

  
  interface Article {
    id: number;
    title: string;
    author: string;
    date: string;
  }
  
  interface LikedData {
    id: number;
    title: string;
    thumbnail: string;
  }
  
  // 视频数据
  const books = ref<Book[]>([]);
  const totalBooks = ref(0);  // 用于存储视频的总条数
  const bookPage = ref(1);
  const bookPageSize = ref(6);
  
  // 文章数据
  const articles = ref<Article[]>([]);
  const totalArticles = ref(0);  // 用于存储文章的总条数
  const articlePage = ref(1);
  const articlePageSize = ref(5);

  const selectedLikeType = ref('articles');
  
  // 喜欢的文章数据
  const likedArticles = ref<Article[]>([]);
  const totalLikedArticles = ref(0);  // 喜欢的文章总条数
  const likedArticlePage = ref(1);
  const likedArticlePageSize = ref(5);
  
  // 喜欢的数据
  const likedData = ref<LikedData[]>([]);
  const totalLikedData = ref(0);  // 喜欢的数据总条数
  const likedDataPage = ref(1);
  const likedDataPageSize = ref(6);
  
  // 从后端 API 获取分页数据的通用函数
  const fetchData = async (url: string, pageNum: number, pageSize: number, dataRef: any, totalRef: any) => {
    try {
        console.log('fetchData:', url, pageNum, pageSize);
      const response = await axios.get(url, {
        params: {  pageNum, pageSize }
      });
    //   dataRef.value = response.data.items;
    //   totalRef.value = response.data.total;
    console.log('response:', response);
    
          dataRef.value = response.data.data.listData;
      totalRef.value = response.data.data.totalRecords;
    } catch (error) {
      console.error('数据获取失败:', error);
    }
  };
  
  // 获取书籍数据
  const fetchBooks = (page = 1, pageSize = 6) => fetchData('/api/books/author/'+props.userId, page, pageSize, books, totalBooks);
  
  // 获取文章数据
  const fetchArticles = (page = 1, pageSize = 5) => fetchData('/api/books/all', page, pageSize, articles, totalArticles);
  
  // 获取喜欢的文章数据
  const fetchLikedArticles = (page = 1, pageSize = 5) => fetchData('/api/liked-articles', page, pageSize, likedArticles, totalLikedArticles);
  
  // 获取喜欢的数据
  const fetchLikedData = (page = 1, pageSize = 6) => fetchData('/api/votes/book_by_userId/'+props.userId, page, pageSize, likedData, totalLikedData);
  
  // 组件挂载时加载数据
  onMounted(() => {
    fetchBooks(bookPage.value, bookPageSize.value);
    fetchArticles(articlePage.value, articlePageSize.value);
    fetchLikedArticles(likedArticlePage.value, likedArticlePageSize.value);
    fetchLikedData(likedDataPage.value, likedDataPageSize.value);
  });
  
  // 分页事件处理
  const handlePageChange = (
  newPage: number, 
  pageSize: number, 
  fetchFn: (page: number, pageSize: number) => void
) => {
  fetchFn(newPage, pageSize);
};
  
  const handleBookPageChange = (newPage: number, pageSize: number) => {
    bookPage.value = newPage;
    handlePageChange(newPage,pageSize, fetchBooks);
  };
  
  const handleArticlePageChange = (newPage: number, pageSize: number) => {
    articlePage.value = newPage;
    handlePageChange(newPage,pageSize, fetchArticles);
  };
  
  const handleLikedArticlePageChange =(newPage: number, pageSize: number)=> {
    likedArticlePage.value = newPage;
    handlePageChange(newPage,pageSize,  fetchLikedArticles);
  };
  
  const handleLikedDataPageChange = (newPage: number, pageSize: number) => {
    likedDataPage.value = newPage;
    handlePageChange(newPage,pageSize,  fetchLikedData);
  };

  const viewArticle = (article: Article) => {
   router.push("/book_show/"+article.id)
  };
  const viewBook = (book: Book) => {
    // 在这里处理查看文章的逻辑，例如跳转到文章详情页面
    router.push("/book_show/"+book.id)
  };
  </script>
  
  
<style scoped>
.home-page {
  padding: 20px;
  display: block;
}


.book-thumbnail,
.like-thumbnail {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.book-title,
.like-title {
  font-weight: bold;
  display: block;
  margin-bottom: 10px;
}

.el-card {
  cursor: pointer;
  transition: box-shadow 0.3s;
  margin-bottom: 20px;
  display: block;
  width: 100%;
}

.el-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.my-book-list,
.my-article-list,
.my-like-list {
    display: flex;

    width: calc(100% - 40px);
  margin-bottom: 40px;
}
.el-main-book{
    display: grid;
  grid-template-columns: repeat(3, 1fr);
  width: auto;
  gap: 20px;
  padding: 20px;
}
.book-card {
 
   
   width: auto;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 10px;
    transition: box-shadow 0.3s ease-in-out;
  }
  
  .book-card:hover {
    box-shadow: 0px 8px 16px rgba(0, 0, 0, 0.1);
  }
  
  .book-thumbnail-wrapper {
    width: 120px;
    flex-shrink: 0;
    margin-right: 20px;
  }
  
  .book-thumbnail {
    width: 100%;
    height: 180px;
    object-fit: cover;
    border-radius: 4px;
  }
  
  .book-info-wrapper {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    flex-grow: 1;
  }
  
  .book-title {
    font-weight: bold;
    margin-bottom: 5px;
  }
  
  .book-description {
    color: var(--bReadContentColor);
    margin-bottom: 8px;
  }
  
  .book-details {
    color: var(--bReadContentColor);
    font-size: 12px;
  }
  
  .el-button {
    align-self: flex-start;
  }
h2 {
  font-size: 24px;
  margin-bottom: 20px;
}

h3 {
  font-size: 18px;
  margin: 0 0 10px 0; /* Adds space between title and paragraph */
}

p {
  margin-bottom: 10px;
}
.book-card-content{
    width: auto;
    flex-direction: column;
    display: flex;
}

</style>
